package com.wheel.mybatis.typeHandler;

import org.apache.ibatis.type.*;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

@Alias("blobToBase64TypeHandler")
@MappedTypes(String.class)
@MappedJdbcTypes({JdbcType.BLOB})
public class BlobToBase64StringTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int parameterIndex, String base64String, JdbcType jdbcType) throws SQLException {
        byte[] x = Base64Utils.decodeFromString(base64String);
        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(x);) {
            ps.setBlob(parameterIndex, inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Blob blob = rs.getBlob(columnName);
        if (blob != null) {
            try (InputStream binaryStream = blob.getBinaryStream();) {
                return Base64Utils.encodeToString(inputStreanToByte(binaryStream));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Blob blob = rs.getBlob(columnIndex);
        if (blob != null) {
            try (InputStream binaryStream = blob.getBinaryStream();) {
                return Base64Utils.encodeToString(inputStreanToByte(binaryStream));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int parameterIndex) throws SQLException {
        Blob blob = cs.getBlob(parameterIndex);
        if (blob != null) {
            try (InputStream binaryStream = blob.getBinaryStream();) {
                return Base64Utils.encodeToString(inputStreanToByte(binaryStream));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private byte[] inputStreanToByte(InputStream inputStream) throws IOException {
        byte[] b = new byte[4096];
        int len;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        while ((len = inputStream.read(b)) != -1) {
            outputStream.write(b, 0, len);
        }
        return outputStream.toByteArray();
    }
}